const https = require('https');
const fs = require('fs');
const url = 'https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png'; // 图片链接

// 创建文件写入流
const fileWriteStream = fs.createWriteStream('baidu_logo.png');

// 发起GET请求，获取图片数据
const request = https.get(url, (response) => {
  if (response.statusCode === 200) {
    response.pipe(fileWriteStream); // 将响应流直接管道到文件写入流

    fileWriteStream.on('finish', () => {
      console.log('Image downloaded successfully.');
      fileWriteStream.close(); // 关闭写入流
    });
  } else {
    console.error(`Failed to download image. Server responded with status code ${response.statusCode}`);
    fileWriteStream.destroy(); // 错误情况下关闭写入流
  }
});

request.on('error', (error) => {
  console.error('Error occurred during the request:', error.message);
  fileWriteStream.destroy(); // 错误情况下关闭写入流
});